package com.weipt.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author peter.wei 2020/09/10 09:25
 * @version 1.0
 * @company 终生学习
 * @description <br>peter.wei 2020/09/10 09:25 生产者消费者=>线程通讯问题
 * lock  await  signal 三剑客
 **/
public class HelloLockPC2 {

    public static void main(String[] args) {
        LockComunicate pc = new LockComunicate();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                pc.printA();
            }
        }, "A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                pc.printB();
            }
        }, "B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                pc.printC();
            }
        }, "C").start();
    }
}

class LockComunicate{
    private static int num = 0;
    //private static AtomicInteger

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            //需要等待的条件
            while (num!=0){
                condition1.await();
            }
            //执行逻辑
            num++;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            //逻辑执行完毕，通知别人
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            //需要等待的条件
            while (num!=1){
                condition2.await();
            }
            //执行逻辑
            num++;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            //通知别人
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            //需要等待的条件
            while (num!=2){
                condition3.await();
            }
            //执行逻辑
            num++;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            //通知别人
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


